package it.webrules.deploymanager.core.utils;

import it.webrules.deploymanager.core.st.scm.SwitchableDir;
import it.webrules.deploymanager.core.st.scm.Type;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SCMTagUtils {

	public static String getNextTagVersion(List<SwitchableDir> switchableDirs) {

		List<SwitchableDir> tmpSwitchableDirs = new ArrayList<SwitchableDir>();

		for (SwitchableDir switchableDir : switchableDirs) {
			if (switchableDir.type.equals(Type.Tag)) {
				tmpSwitchableDirs.add(switchableDir);
			}
		}

		Collections.sort(tmpSwitchableDirs);
		String nextname = null;

		if (tmpSwitchableDirs.size() > 0) {

			int i = 1;
			SwitchableDir last = tmpSwitchableDirs.get(tmpSwitchableDirs.size() - 1);
			String nmbefore = last.name;
			String nmafter = "";

			Pattern pattern = Pattern.compile("(\\d+)");
			Matcher matcher = pattern.matcher(last.name);

			while (matcher.find()) {
				if (matcher.groupCount() > 0) {
					i = Integer.valueOf(matcher.group(matcher.groupCount()));
					nmbefore = last.name.substring(0, matcher.start(matcher.groupCount()));
					nmafter = last.name.substring(matcher.end(matcher.groupCount()));
				}
			}

			while (nextname == null) {
				if (!alreadyExist(tmpSwitchableDirs, nmbefore + i + nmafter))
					nextname = nmbefore + i + nmafter;
				i++;
			}

		} else {
			nextname = "rel-0.0.1";
		}
		return nextname;
	}

	private static boolean alreadyExist(List<SwitchableDir> switchableDirs, String name) {
		for (SwitchableDir switchableDir : switchableDirs) {
			if (switchableDir.name.equals(name))
				return true;
		}
		return false;
	}
}
